const app = getApp()
const request = require('../../../utils/request.js');
Page({
  data: {
    title: '',
    content: ''
  },

  // 标题输入
  onTitleInput: function(e) {
    this.setData({
      title: e.detail.value
    })
  },

  // 内容输入
  onContentInput: function(e) {
    this.setData({
      content: e.detail.value
    })
  },

  // 表单验证
  validateForm: function() {
    const { title, content } = this.data
    
    if (!title) {
      wx.showToast({
        title: '请输入咨询标题',
        icon: 'none'
      })
      return false
    }

    if (!content) {
      wx.showToast({
        title: '请输入详细描述',
        icon: 'none'
      })
      return false
    }

    return true
  },

  // 提交咨询
  submitConsultation: function() {
    if (!this.validateForm()) return

    if (!app.getGlobalToken()) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }

    wx.showLoading({
      title: '发布中...',
    })

    const { title, content } = this.data

    request.request({
      url: `${app.globalData.baseUrl}/api/consultation/questions`,
      method: 'POST',
      data: {
        title,
        content
      },
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '发布成功',
            icon: 'success'
          })
          // 发布成功后返回上一页
          app.globalData.needRefresh = true;
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.data.message || '发布失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
}) 